package com.atguigu.ucenter.controller;

import com.atguigu.common.R;
import com.atguigu.common.jwt.JwtUtils;
import com.atguigu.servicebase.exceptionhandler.ELeanExeception;
import com.atguigu.ucenter.entity.Member;
import com.atguigu.ucenter.service.MemberService;
import com.atguigu.ucenter.utils.ConstantWxUtils;
import com.atguigu.ucenter.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author panghl
 * @Date 2021/2/6 21:27
 * @Description TODO
 **/
//注意这里没有配置 @RestController
@Controller
@RequestMapping("/educenter/api/ucenter/wx/")
@Api(tags = {"微信接口"})
public class WxApiController {

    @Autowired
    private MemberService memberService;

    @ApiOperation(value = "生成微信二维码")
    @GetMapping("login")
    public String getWxCode() {
//        String url= "https://open.weixin.qq.com/connect/qrconnect" +
//                "?appid="+ ConstantWxUtils.WX_OPEN_APP_ID+"&response_type=code";


        //微信开放平台授权baseUrl   %s相当于?代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对redirect_url 进行URLEncoder编码
        String redirect_url = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirect_url = URLEncoder.encode(redirect_url, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }


        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
//        String state = "imhelen";//为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名
//        System.out.println("state = " + state);

        // 采用redis等进行缓存state 使用sessionId为key 30分钟后过期，可配置
        //键："wechar-open-state-" + httpServletRequest.getSession().getId()
        //值：satte
        //过期时间：30分钟

        //给baseUrl %s 里面 设置值
        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_REDIRECT_URL,
                "atguigu");


        //重定向到请求微信地址里面请求微信地址
        return "redirect:" + url;
    }


    @ApiOperation(value = "获取扫描人信息，添加数据")
    @GetMapping("callback")
    public String callback(String code, String state) {
        try {
            //从redis中将state获取出来，和当前传入的state作比较
            //如果一致则放行，如果不一致则抛出异常：非法访问

            //向认证服务器发送请求换取access_token
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //拼接三个参数：id 秘钥 和code值
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code);

            //请求这个拼接好的地址，得到返回两个值， access_token 和openid
            //使用httpclient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessToken=============" + accessTokenInfo);

            //gson转换工具
            Gson gson = new Gson();
            HashMap<String,String> mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String accessToken = mapAccessToken.get("access_token");
            String openid = mapAccessToken.get("openid");

            //判断数据表里面是否有相应对的数据，根据openid判断
            Member member= memberService.getOpenIdMember(openid);
            if (member == null){
//                return "redirect:http://localhost:3000?code=" + code + "&state=" + state;
                //3 拿着得到access_token值 获取登录用户信息
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                //拼接两个参数
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        accessToken,
                        openid);
                //发送请求
                String userInfo = HttpClientUtils.get(userInfoUrl);

                //获取返回userInfo字符串扫描人信息
                HashMap<String,String> userInfoMap= gson.fromJson(userInfo, HashMap.class);
                String nickname = userInfoMap.get("nickname");
                String headimgurl = userInfoMap.get("headimgurl");
                //把扫描人信息添加数据库里面
                member = new Member();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }
            //使用jwt根据member对象生成token字符串
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            //最后:返回首页面，通过路径传递token字符串
            return "redirect:http://localhost:3000?token="+jwtToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ELeanExeception(20001, "登录失败");
        }
    }
}
